/**
 * Created by HuQiang on 2017/7/30.
 */
import React from 'react';
import {Radio, Input, Modal} from 'antd'
import {LineChart, Line, XAxis, YAxis} from 'recharts';
import $ from "jquery";
import Counter from "./Counter";
require("./Question.css");
const RadioGroup = Radio.Group;
const {TextArea} = Input;
require("./Counter");

//$ npm install recharts

let question = [];
let question_id = [];
let answer = [];
let option = [];
let analysis = [];
let user_answer = [];
let user_whether_true = [];
let score = [];
let user_score = 0;
let date = new Date();

let dataList = [];

const line_data = [{name: "java 基础", value: 20}, {name: "数据结构", value: 5}, {name: "TCP/IP", value: 10},
    {name: "数据库", value: 10}];
export default class Question extends React.Component {
    constructor(props) {
        super(props);
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem("userStorage"));
        this.state = {
            question_type_id: 1,
            exam_type_id: 2,
            number: 5,
            user_id: userSessionStorage.data.id,
            modal_visible: false,
            true_answer_display: "none",
            use_time: "",
            exam_score: 0,
            year: date.getYear() + 1900,
            month: date.getMonth() + 1,
            date: date.getDate(),
            hour: date.getHours(),
            minutes: date.getMinutes(),
            seconds: date.getSeconds(),
            radio_disabled: false,
        };
    }


    componentWillMount() {
        question.length = 0;
        answer.length = 0;
        option.length = 0;
        user_answer.length = 0;
        dataList.length = 0;
        this.fetchData(1, 2);
        this.fetchData(2, 2);
        this.fetchData(3, 2);
    };

    fetchData = (question_type_id, exam_type_id) => {
        $.ajax({
            type: "POST",
            url: "http://123.207.214.129:9090/LanOu/getQuestionsByType",
            data: {
                question_type_id: question_type_id,
                exam_type_id: exam_type_id
            },
            async: false,
            dataType: "json",
            success: (data) => {

                this.setState({
                    exam_type_id: exam_type_id
                });
                user_answer.length += data.data.length;
                switch (data.msg) {
                    case "1":
                        for (let i = 0; i < data.data.length; i++) {
                            question.push(data.data[i].content);
                            question_id.push(data.data[i].question_id);
                            answer.push(data.data[i].answer);
                            analysis.push(data.data[i].analysis);
                            score.push(data.data[i].score);
                            option.push({
                                "A": data.data[i].option[0],
                                "B": data.data[i].option[1],
                                "C": data.data[i].option[2],
                                "D": data.data[i].option[3]
                            });
                            dataList.push(
                                <div key={i} className="question-type-1 question-type">

                                    <p className="question-title">{i + 1}.{question[i]}</p>
                                    <div className="options">
                                        <RadioGroup onChange={(e) => {
                                            user_answer[i] = e.target.value;
                                            //检查前面是否有没做的题目

                                            for (let n = 0; n < i; n++) {
                                                if (user_answer[n] === undefined) {
                                                    $('.question-type').eq(n).css('border', '0.02rem solid #FF4500');
                                                }
                                                else {

                                                }
                                            }
                                            $('.question-type').eq(i).css('border', '0.02rem solid #32CD32');

                                        }}>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].A}>{option[i].A}</Radio>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].B}>{option[i].B}</Radio>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].C}>{option[i].C}</Radio>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].D}>{option[i].D}</Radio>
                                        </RadioGroup>
                                    </div>

                                    <div className="answer">
                                        {"正确答案: " + answer[i] + ", 解析: " + analysis[i]}
                                    </div>
                                </div>)
                        }
                        break;
                    case "2":
                        for (let j = 0; j < data.data.length; j++) {
                            const i = question.length;
                            question.push(data.data[j].content);
                            question_id.push(data.data[j].question_id);
                            answer.push(data.data[j].answer);
                            analysis.push(data.data[j].analysis);
                            score.push(data.data[j].score);
                            option.push({
                                "Yes": "是",
                                "No": "否"
                            });
                            dataList.push(
                                <div key={i} className="question-type-2 question-type">
                                    <p className="question-title">{i + 1}.{question[i]}</p>
                                    <div className="options">
                                        <RadioGroup onChange={(e) => {
                                            user_answer[i] = e.target.value;

                                            for (let n = 0; n < i; n++) {
                                                if (user_answer[n] === undefined) {
                                                    $('.question-type').eq(n).css('border', '0.02rem solid #FF4500');
                                                }
                                                else {

                                                }
                                            }


                                            $('.question-type').eq(i).css('border', '0.02rem solid #32CD32');

                                        }}>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].Yes}>{option[i].Yes}</Radio>
                                            <Radio style={radioStyle} disabled={this.state.radio_disabled} value={option[i].No}>{option[i].No}</Radio>
                                        </RadioGroup>
                                    </div>
                                    <div className="answer">
                                        {"正确答案: " + answer[i] + ", 解析: " + analysis[i]}
                                    </div>
                                </div>
                            )
                        }
                        break;
                    case "3":
                        for (let k = 0; k < data.data.length; k++) {
                            const i = question.length;
                            question.push(data.data[k].content);
                            question_id.push(data.data[k].question_id);
                            score.push(data.data[k].score);
                            analysis.push(data.data[k].analysis);
                            answer.push(data.data[k].answer);
                            dataList.push(
                                <div key={i} className="question-type-3 question-type">
                                    <p className="question-title">{i + 1}.{question[i]}</p>
                                    <TextArea rows={4} onChange={(e) => {
                                        user_answer[i] = e.target.value;

                                        for (let n = 0; n < i; n++) {
                                            if (user_answer[n] === undefined) {
                                                $('.question-type').eq(n).css('border', '0.02rem solid #FF4500');
                                            }
                                            else {

                                            }
                                        }
                                        if (e.target.value === "") {
                                            $('.question-type').eq(i).css('border', '0.02rem solid #FF4500');
                                        }
                                        else {
                                            $('.question-type').eq(i).css('border', '0.02rem solid #32CD32');

                                            for (let n = 0; n < i; n++) {
                                                if (user_answer[n] === undefined) {
                                                    $('.question-type').eq(n).css('border', '0.02rem solid #FF4500');
                                                }
                                                else {

                                                }
                                            }
                                            if (e.target.value === "") {
                                                $('.question-type').eq(i).css('border', '0.02rem solid #FF4500');
                                            }
                                            else {
                                                $('.question-type').eq(i).css('border', '0.02rem solid #32CD32');
                                            }
                                        }


                                    }}/>
                                    <div className="answer">
                                        {"参考答案: " + answer[i] + ", 解析: " + analysis[i]}
                                    </div>
                                </div>
                            )
                        }
                        break;
                    default:
                        break;
                }
            },
            error: function (e) {
                console.log(e);
            }
        });
    };

    submitExam = (e) => {
        e.preventDefault();
        let questionStringBuilder = "";
        let answerStringBuilder = "";
        let exam_score = 0;
        let now = new Date();
        for (let i = 0; i < user_answer.length; i++) {
            exam_score += score[i];
            if (user_answer[i] === undefined) {
                user_answer[i] = "";
            }
            user_answer[i] = user_answer[i].charAt(0);
            if (user_answer[i] === answer[i]) {
                user_score += score[i];
                user_whether_true[i] = true;
            } else {
                user_score += 0;
                user_whether_true[i] = false;
            }
            if (i === user_answer.length - 1) {
                questionStringBuilder += question_id[i];
                answerStringBuilder += user_answer[i];
            } else {
                questionStringBuilder += question_id[i] + '|';
                answerStringBuilder += user_answer[i] + '|';
            }
        }
        const begin = this.state.year + "/" + this.state.month + "/" + this.state.date + " " + this.state.hour + ":" + this.state.minutes;
        const finish = now.getHours() * 60 * 60 + now.getMinutes() * 60 + now.getSeconds() - this.state.hour * 60 * 60 - this.state.minutes * 60 - this.state.seconds;
        const hour = parseInt(finish / 60 / 60);
        const min = parseInt(finish / 60);
        const sec = finish % 60;
        const time = hour + ':' + min + ':' + sec;
        this.setState({
            use_time: time,
            exam_score: exam_score
        });
        $.ajax({
            type: "POST",
            url: "http://123.207.214.129:9090/LanOu/saveExamHistory",
            data: {
                user_id: this.state.user_id,
                h_score: user_score,
                exam_type_id: this.state.exam_type_id,
                begin: begin,
                time_limit: 50,
                use_time: time,
                questions: questionStringBuilder,
                answers: answerStringBuilder
            },
            dataType: "json",
            success: (data) => {
                console.log(data)
            },
            error: function (e) {
                console.log(e);
            }
        });
        this.setState({
            modal_visible: true
        });
    };

    handleCancel = () => {

        for(let n = 0; n < user_whether_true.length ; n++)
        {
            if(user_whether_true[n])
            {
                $('.answer').eq(n).css('color','#32CD32')
            }
            else
            {
                $('.answer').eq(n).css('color','#FF4500')
                $('.question-type').eq(n).css('border', '0.02rem solid #FF4500');
            }
            console.log(user_whether_true[n])
        }

        $('.answer').css('display', 'block');

        this.setState({
            radio_disabled: true,
            modal_visible: false
        });
    };

    handleSubmit = () => {
        this.handleCancel()
    };

    render() {
        return (
            <div className="main">
                <form onSubmit={(e) => this.submitExam(e)}>
                    <div className="title">
                        <label className="title-text">剩余时间 :<Counter value={59} step={1} mode={2}/><label>:</label><Counter value={59} step={1} mode={1}/></label>
                        <button className="btn-submit" type="submit">提交试卷</button>
                    </div>
                </form>
                <Modal
                    title="考试结果"
                    wrapClassName="vertical-center-modal"
                    visible={this.state.modal_visible}
                    onOk={this.handleSubmit}
                    onCancel={this.handleCancel}
                    okText="确定"
                    width="700px">
                    <p className="judge">
                        您的成绩:{user_score + "/" + this.state.exam_score}
                    </p>
                    <p className="judge">
                        考试时间:{this.state.use_time}
                    </p>
                    <p className="judge">
                        分析:你的Java基础知识掌握得很牢固，继续加油。数据库和TCP/IP掌握得还不错，请继续
                    </p>

                    <p className="judge">
                        努力。数据结构模块相对比较薄弱，请抓紧学习，不要让他成为你求职路上的绊脚石！
                    </p>

                    <div>
                        <LineChart width={600} height={400} data={line_data}>
                            <XAxis dataKey="name"/>
                            <YAxis dataKey="value"/>
                            <Line type="monotone" stroke="#8884d8" dataKey="value"/>
                        </LineChart>
                    </div>

                </Modal>
                <div className="section">
                    {dataList}
                </div>
            </div>
        );
    };
}
const radioStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
};
// const counterStyle= {
//     fontSize: '1.6rem',
//     color: '#0f88eb',
//     marginLeft: '2rem',
//     marginTop: '1.3rem',
//     display: 'inline-block'
// };